package com.cu.employmentmanagementsystem.controller;

import cn.dev33.satoken.annotation.SaIgnore;
import com.cu.employmentmanagementsystem.handler.WxChatMsgHandler;
import com.cu.employmentmanagementsystem.handler.WxChatMsgHandlerFactory;
import com.cu.employmentmanagementsystem.util.MessageUtil;
import com.cu.employmentmanagementsystem.util.SHA1;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Map;

/**
 * @author CaptainUniverse_
 */
@RestController
@Slf4j
@SaIgnore
public class CallBackController
{
    private static final String CACHE_KEY_SEPARATOR = ".";

    private static final String TOKEN = "adwidhaidwoaid";
    @Resource
    private WxChatMsgHandlerFactory wxChatMsgHandlerFactory;

    /**
     * 回调消息校验
     */
    @RequestMapping(value ="/callback",produces = "text/plain;charset=UTF-8")
    public String callback(@RequestParam("signature") String signature,
                           @RequestParam("timestamp") String timestamp,
                           @RequestParam("nonce") String nonce,
                           @RequestParam("echostr") String echostr) {
        log.info("get验签请求参数：signature:{}，timestamp:{}，nonce:{}，echostr:{}",
                signature, timestamp, nonce, echostr);
        String shaStr = SHA1.getSHA1(TOKEN, timestamp, nonce, "");
        if (signature.equals(shaStr)) {
            return echostr;
        }
        return "unknown";
    }

    @PostMapping(value = "/callback", produces = "application/xml;charset=UTF-8")
    public String callback(
            @RequestBody String requestBody,
            @RequestParam("signature") String signature,
            @RequestParam("timestamp") String timestamp,
            @RequestParam("nonce") String nonce,
            @RequestParam(value = "msg_signature", required = false) String msgSignature) {
        log.info("接收到微信消息：requestBody：{}", requestBody);
        Map<String, String> messageMap = MessageUtil.parseXml(requestBody);
        String msgType = messageMap.get("MsgType");
        String event = messageMap.get("Event") == null ? "" : messageMap.get("Event");

        StringBuilder stringBuilder = new StringBuilder(msgType);
        if(!event.isEmpty())
        {
            stringBuilder.append(CACHE_KEY_SEPARATOR).append(event);
        }
        String msgTypeKey = stringBuilder.toString();

        WxChatMsgHandler handler = wxChatMsgHandlerFactory.getHandlerByMsgType(msgTypeKey);
        String replyContent = handler.dealMsg(messageMap);


        return replyContent;
    }

    /**
     * 构建缓存key
     */
    public String buildKey(String... strObjs) {
        return String.join(CACHE_KEY_SEPARATOR, strObjs);
    }

}
